require('swiper/css/swiper.css')
require('../scss/vita/vita.scss')
require('../scss/index.scss')

var Swiper = require('swiper/js/swiper')

var APP = {

  //用于保存dom对象引用
  $els: {},

  init: function() {

    this.bindEvent();
    this.initData(function(){
      checkTicketStatus(function(ticket){  
                 APP.getData(ticket)
            },true,function(){showLoginBox();})
    });

    // 在此判断已开通未开通
    if (false) {
      this.initIsMember()
    } else {
      this.initNotMember()
    }

  },

  //初始化未开通真爱团的页面
  initNotMember: function() {
    $('#not-member-page').show()
    this.$els.introsSwiper = new Swiper('.swiper-container', {
      autoplay: 3000,
      autoplayDisableOnInteraction: true
    })
  },
  // 初始化已开通珍爱团的界面
  initIsMember: function() {
    var _this = this

    $.extend(this.$els, {
      btnRenew: $('.btn-renew'),
      btnQuestion: $('.question'),
      tip: $('.tip')
    })

    $('#is-member-page').show()
    $('.base-info').addClass('is-open')

    //续费按钮点击
    this.$els.btnRenew.on('click', function() {
      console.log(123)
    })
    // 问号按钮点击
    this.$els.btnQuestion.on('click', function() {
      _this.$els.tip.show()
    })
  },

  bindEvent: function() {
    // 此方法用以修复iOS上无法启用:active的bug
    document.body.addEventListener('touchstart', function () {}); 
  },

  data: {
    piUid:$.url.param("piUid"),
    topSid : $.url.param("topSid"),
    subSid : $.url.param("subSid"),
    userUid :$.url.param("userUid"),
    inChannel : $.url.param("inChannel"),
    source : "2",
    operatorType : "0", //0 开通，1 续费
    selectedMonths : "1", //默认开通一个月
    id :"#not-member-page",  //默认开通
    isAjaxOver : true,
    postUrl:'http://m.yy.com/earn/',
    url: 'cherish/openCherish.action',
    duowanCallback:'callbackForopenCherish',
    zhenaiAppStoreID:{ "productId":"yyvoice.iap",
                       "productType":1,
                       "newZ":{"1":{"id":"yyvoice.iap.zhenai.01.new",
                                    "name":"zhenai.01.new",
                                    "productDesc":"特权一开通",
                                    "price":6},
                               "2":{"name":"zhenai.10.new",
                                    "id":"yyvoice.iap.zhenai.10.new",
                                    "productDesc":"特权二开通",
                                    "price":18},
                               "3":{"name":"zhenai.100.new",
                                    "id":"yyvoice.iap.zhenai.100.new",
                                    "productDesc":"特权三开通",
                                    "price":148},
                               "buyType":0
                              },
                       "renew":{"1":{"name":"zhenai.01.renew",
                                     "id":"yyvoice.iap.zhenai.01.renew",
                                     "productDesc":"特权一续费",
                                     "price":6
                                    },
                                "2":{"name":"zhenai.10.renew",
                                     "id":"yyvoice.iap.zhenai.10.renew",
                                     "productDesc":"特权二续费",
                                     "price":18
                                    },
                                "3":{
                                     "name":"zhenai.100.renew",
                                     "id":"yyvoice.iap.zhenai.100.renew",
                                     "productDesc":"特权三续费",
                                     "price":148
                                    },
                                "buyType":1
                                }
                      }

  },

  initData: function(callBack){
    try{
        APP.data.mac = window.YYApiCore.invokeClientMethod('data', 'getMac');
        if(typeof  APP.data.mac !== 'string'){
             APP.data.mac = '';
        }else{
            APP.data.mac = APP.data.mac.replace(/\%3A/g,':');
        }

    }
    catch(err){
         APP.data.mac='';
    }
    try{
        APP.data.imei = window.YYApiCore.invokeClientMethod('data', 'getImei');
         if(typeof APP.data.imei !== 'string'){
            APP.data.imei = '';
        }
    }
    catch(err){
       APP.data.imei='';
    }
    try{
        APP.data.channelSource = window.YYApiCore.invokeClientMethod('data', 'getChannelSource');
         if(typeof APP.data.channelSource !== 'string'){
            APP.data.channelSource = '';
        }
    }
    catch(err){
         APP.data.channelSource = '';
    }
    try{
        APP.data.yyVersion = window.YYApiCore.invokeClientMethod('data', 'getYYVersion');
         if(typeof APP.data.yyVersion !== 'string'){
            APP.data.yyVersion = '';
        }
    }
    catch(err){
        APP.data.yyVersion = '';
    }
    if(isIos){
      try{
            APP.data.noYB = window.YYApiCore.invokeClientMethod('data', 'isFromAppStore', {});
            if(typeof APP.data.noYB === 'undefined' || APP.data.noYB != 1){
                APP.data.noYB = '';
            }
                         
        }
       catch(err){
        APP.data.noYB = '';
        }
    }
    if(typeof callBack == 'function')
      callBack();

  },

  getData: function(ticket){
    var param ={};
    param.anchorUid = $.url.param("piUid");
    param.topSid = $.url.param("topSid");
    param.subSid = $.url.param("subSid");
    param.userUid = $.url.param("userUid");
    param.inChannel = $.url.param("inChannel");
    param.source = "2";
    param.ticket = ticket;
    $.ajax({
            dataType : 'json'
            ,type : 'POST'
            ,url : 'http://m.yy.com/earn/cherish/isAnchoidOrUidV2.action'
            ,data : param
            ,cache : false
            ,timeout : 10000
            ,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
            ,success : function(json){
                        APP.data.isAnchorUid = json.isAnchoid;
                        APP.data.isOpenCherish = json.isOpenCherish;
                        APP.data.isCherishExpire = json.isExpire;
                        APP.data.cherishGroupInfo = json.cherishGroupInfo;
                        APP.data.anchorNick = json.anchorNick;
                        APP.cherishRender();
            }
            ,error: function(XMLHttpRequest, textStatus, errorThrown){
                  
            }
  }); 
  },

  cherishRender: function(){
    //this.anchorRender();
    //return;
    if(this.data.isAnchorUid){
      this.anchorRender();
    }else{
      if(this.data.isOpenCherish){
        if(this.data.isCherishExpire){
          this.openRender();
        }else{
          this.renewRender();
        }
      }else{
        this.openRender();
      }
    }

  },

  anchorRender: function(){
    this.baseInfoRender();
    checkTicketStatus(function(ticket){   
                       APP.getTaskData(ticket)
                      },true,function(){showLoginBox();});
    $('#open-page .btn').show().text('设置').unbind().bind('click',function(){
      gotoPage('http://172.19.99.56:8899/setting.html?piUid=440735597&topSid=0&subSid=0&level=1&inChannel=false&userUid=1309403068');
    });
    this.initIsMember();
    $('#not-member-page').hide();
    $('#is-member-page').show();
  },

  openRender: function(){
    this.baseInfoRender();
    this.buttonRender();
    $('#open-page .btn').hide();
    $('#is-member-page').hide();
    $('#not-member-page').show();
  },

  renewRender: function(){
    APP.data.id = "#renew-page";
    APP.data.operatorType = "1";
    APP.data.url = 'cherish/renewCherish.action';
    APP.data.duowanCallback = 'callbackForXufei';
    this.baseInfoRender();
    this.buttonRender();
    this.initIsMember();
    checkTicketStatus(function(ticket){   
                       APP.getTaskData(ticket)
                      },true,function(){showLoginBox();});
    $('#open-page .btn').show().unbind().bind('click',function(){
      $('#open-page').hide();
      $('#renew-page').show();
    });
    $('#not-member-page').hide();
    $('#is-member-page').show();
  },

  baseInfoRender: function(){
    var groupInfo = this.data.cherishGroupInfo;
    $('#open-page .group-name').html(this.data.anchorNick+'的珍爱团');
    var rank = parseInt(groupInfo.rank);
    if(rank>99){
      $('#open-page .rank').html('NO.<br><span>99+</span>');
    }else{
      $('#open-page .rank').html('NO.<br><span>'+rank+'</span>');
    }
    var groupImg = groupInfo.cardpic;
    if(groupImg){
      groupImg = "http://image.yy.com/earn/"+groupImg+"?imageview/0/w/116/h/116";
    }else{
      groupImg = "http://earn.yystatic.com/earn/images/cherish/v2/pc/default_za.jpg";
    }
    //$('#open-page .avatar').html('<img src="'+groupImg+'" />');
    $("#open-page .avatar").css('background-image','url('+groupImg+')');
    $('#open-page .group-info .name').text(groupInfo.medalname);
    $('#open-page .group-info .count').text(groupInfo.numb);
    $('#open-page .group-info .lv').text('LV'+groupInfo.weekRank);
    $('#open-page .group-info .text').text(groupInfo.numb);
    if(APP.data.operatorType = "1"){
      $('#renew-page .red').text(groupInfo.usrEndTime.substring(0,10));
    }
  },

  buttonRender:function(){
    $(this.data.id+' .price').bind('click',function(){
      APP.data.selectedMonths = $(this).attr('data-month');
      APP.openCherish();
    });
  },

  getTaskData:function(ticket){
    $.ajax({
        dataType : 'json'
        ,type : 'POST'
        ,url : 'http://m.yy.com/earn/cherish/queryCherishGroupTask.action'
        ,data : {anchorUid : $.url.param('piUid'),ticket:ticket}
        ,cache : false
        ,timeout : 10000
        ,contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
        ,success : function(json){
          if(json.result == '0'){
            APP.data.taskInfo = json;
            APP.taskRender();
          }
        }
        ,excetpion: function(json){
        }
    });
  },

  taskRender: function(){
    for(var i = 0;i < 2;i ++){
      var id = i==0?"#task-login":"#task-gift";
      var data = this.data.taskInfo.finQuest[i];
      var finish = parseInt(data.finMenber);
      var score = data.finMenber
      if(finish==0){
        $(id).removeClass('done');
        $(id+' .desc').text('暂无铁粉完成');
      }else{
        $(id+' .desc').text(finish+'铁粉完成');
        var finishTime = parseInt(data.finTime);
        if(finishTime=='0'){
          $(id).removeClass('done');
        }else{
          $(id).addClass('done');
        }
      }
    }
  },

openCherish: function(){
  //report
  reportPhoneCherishEvent(1,this.data.piUid);
  if (APP.data.isAjaxOver) {
          APP.data.isAjaxOver = false;
          getAppInfo(function(info) {
            requestUserWebToken(function(ticket) {
            //update below ajax request info.systemVersion->info.appVersion
            if(APP.data.isRMBPay&&isIos&&APP.data.noYB=='1'){
                var parms={};
                var newZ = APP.data.zhenaiAppStoreID.newZ['1'];
                parms.productId = newZ.id;
                parms.productType = APP.data.zhenaiAppStoreID.productType;
                parms.name = newZ.name;
                parms.productDesc = newZ.productDesc;
                parms.price = newZ.price;
                parms.buyType = APP.data.zhenaiAppStoreID.newZ.buyType;
                parms.userId = APP.data.userUid;
                parms.anchorId = APP.data.piUid;
                APP.data.isAjaxOver = true;
                //blockbg();
                window.YYApiCore.invokeClientMethod('data', 'requesetOpenNobleOrTrueLove',parms,"requestCallBackFun");
            }else{
                  $.ajax({
                      dataType: 'json',
                      type: 'POST',
                      url: APP.data.postUrl + APP.data.url,
                      data: {
                          ticket: ticket,
                          level:'1',
                          months:APP.data.selectedMonths,
                          uuid: APP.data.gUUID,
                          agentId: APP.data.piUid,
                          userUid: APP.data.userUid,
                          source:2,
                          partner:info.system+'-'+info.appVersion,
                          systemName: info.system,
                          systemVersion: info.appVersion,
                          mac:APP.data.mac,
                          imei:APP.data.imei,
                          channelSource:APP.data.channelSource,
                          yyVersion:APP.data.yyVersion
                      },
                      cache: false,
                      timeout: 100000,
                      contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                      complete: function() {
                           APP.data.isAjaxOver = true;
                      },
                      success: function(data) {
                          if (data.result == "0" && !data.confirmUrl && data.moneyType) {                    
                              msg = data.notifyText;
                              showMobileAlertThree(msg, function(index) {
                                  var choice;
                                  switch (index) {
                                      case 0:
                                          choice = 1;
                                          break;
                                      case 2:
                                          choice = 2;
                                          break;
                                      default:
                                          choice = 3;
                                          $("#gz-mark").hide();
                                          $("#three").hide();
                                          return;
                                  }
                                  $.ajax({
                                      dataType: 'json',
                                      eventTarget: 'req',
                                      type: 'POST',
                                      url: APP.data.postUrl + 'cherish/confirmPay.action',
                                      data: {
                                          ticket: ticket,
                                          userChoice: choice,
                                          orderId: data.orderId,
                                          userUid: APP.data.userUid,
                                          appData: data.appData
                                      },
                                      cache: false,
                                      timeout: 1000000,
                                      contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                                      success: function(data0) {
                                          if (data0.result == 0) {
                                              //context.openCherishSuccess();
                                              //reportEvent("10004781", "3"); //购买成功
                                          } else {
                                              $('#submitBtn').removeAttr('disabled').removeClass('greybg');
                                              failResult(data0.result);
                                          }
                                      }
                                  });
                                  $("#gz-mark").hide();
                                  $("#three").hide();
                              });

                          } else if (data.result == "0" && data.confirmUrl) { //多玩币
                              pay.JsLoader.loadAuthDivForUrl({
                                  info: data.confirmUrl + "&theme=orange"
                              },APP.data.duowanCallback);
                          } else if (data.result == "0") {
                              //cherishHandler.openCherishSuccess();
                              var param = {"type": "1", // 1表示带勋章名，2为有效期
                                           "title": "开通珍爱提示",
                                           "des": {
                                                  "text": "你已获得粉丝勋章",
                                                  "medal": "勋章名", //type=2可不加该字段
                                                  "colorArray": [    //传黄色文字文字部分，
                                                                  {
                                                                    "range": "{1, 1}",  // 表示index=1，len=1，
                                                                    "color": 255    // 颜色值
                                                                  },
                                                                  {
                                                                    "range": "{3, 2}",
                                                                    "color": 0
                                                                  }
                                                                ]
                                                 },
                                           "buttons":["知道了","佩戴勋章"]
                                          };
                              this.operatorSuccess(param,function(){
                                alert(2)
                              });
                          } else {
                              APP.operatorFail(data.result);
                          }
                      },
                      error:function(data){
                             //$('#submitBtn').removeAttr('disabled').removeClass('greybg');
                             return;
                      }
                  });
            }
              });
          });
  } else {
      $('#submitBtn').removeAttr('disabled').removeClass('greybg');
      return;
     

  }
},

operatorSuccess: function(param,callBack){
    window.YYApiCore.invokeClientMethod(
      'ui',
      'showTrueLoveAlertDialog',
     /* {"type": "1", // 1表示带勋章名，2为有效期
       "title": "开通珍爱提示",
       "des": {
              "text": "你已获得粉丝勋章",
              "medal": "勋章名", //type=2可不加该字段
              "colorArray": [    //传黄色文字文字部分，
                              {
                                "range": "{1, 1}",  // 表示index=1，len=1，
                                "color": 255    // 颜色值
                              },
                              {
                                "range": "{3, 2}",
                                "color": 0
                              }
                            ]
             },
       "buttons":["知道了","佩戴勋章"]
      },*/
      param,
      function(resp) {
            callBack();
            }
     );

},

operatorFail: function(result){
  var resultDesc = '';
  if(result == 103002 || result ==103168){ // 余额不足
    resultDesc = getResultDesc(result);
    var btnDesc = "充值";
    var chargeLink = "yymobile://Common/RechargeCenter";
    if(result == 103002 && isIos){
      var noYB = '';        
      try{        
            noYB = window.YYApiCore.invokeClientMethod('data', 'isFromAppStore', {});
            if(typeof noYB === 'undefined' || noYB != 1){
                noYB = '';
            }
                         
        }
       catch(err){
          noYB = '';
        }
       if(typeof noYB !== 'undefined' && noYB == 1){
        chargeLink = "yymobile://Common/AccountCenter";
        resultDesc = "对不起，您的红钻数量已不足，用Y币兑换？";
        btnDesc = "确定";
       }
    }
    //for iOS version >= 3.14,payment is using red diamond instead of YB end
    var param = {
      "title": "提示",
      "message": resultDesc,
      "buttons":[btnDesc]
    }
    this.alert(param,function(){_goto(chargeLink)});
    return;
  }else if(result == 103017 ){ // 娱乐套件V4.0删档内测提示(不支持Y币支付)
    resultDesc = getResultDesc(result);
    var param = {
      "title": "提示",
      "message": resultDesc,
      "buttons":["确定"]
    }
    this.alert(param,function(){});
    return;
  }else{ //其它
    resultDesc = getResultDesc(result);
    var param = {
      "title": "提示",
      "message": resultDesc,
      "buttons":["确定"]
    }
    this.alert(param,function(){});
    return;
  }
},

alert: function(param,callBack){
  window.YYApiCore.invokeClientMethod(
    'ui',
    'showAlertDialog',
    param,
    function(resp) {
      callBack();
    });
}

}

APP.init()